App({
  globalData: {
    currentSong: null,
    currentPlaylist: [],
    currentSongIndex: 0,
    playlist: [],
    isPlaying: false,
    playMode: 'list', // list: 列表循环, loop: 单曲循环, random: 随机播放
    audioManager: null,
    userInfo: null,        // 用户信息
    playHistory: [],       // 播放历史记录
    favorites: [],         // 收藏歌曲列表
    userPlaylists: [],     // 用户创建的歌单
    songs: [],             // 所有歌曲数据
    settings: {            // 用户设置
      quality: 1,          // 音质：0-标准，1-高品质，2-无损
      autoPlay: true,      // 自动播放
      nightMode: false     // 夜间模式
    },
    // 添加统计数据
    stats: {
      favoriteCount: 0,    // 收藏数量
      historyCount: 0,     // 播放历史数量
      playlistCount: 0,    // 歌单数量
      downloadCount: 0     // 下载数量
    }
  },
  
  onLaunch() {
    this.globalData.audioManager = wx.getBackgroundAudioManager()
    
    // 初始化歌曲数据
    this.initSongsData()
    
    // 从本地存储加载数据
    this.loadUserData()
    
    this.setupAudioEvents()
    
    // 初始化统计数据
    this.updateStats()
  },

  // 初始化所有歌曲数据
  initSongsData() {
    const config = require('./utils/config')
    const allSongs = []
    
    // 从所有歌单中收集歌曲，并添加歌单ID
    for (let i = 1; i <= 6; i++) {
      const songs = config.getPlaylistSongs(i)
      const songsWithPlaylistId = songs.map(song => ({
        ...song,
        playlistId: i
      }))
      allSongs.push(...songsWithPlaylistId)
    }
    
    this.globalData.songs = allSongs
  },

  // 加载用户数据
  loadUserData() {
    const userInfo = wx.getStorageSync('userInfo')
    const playHistory = wx.getStorageSync('playHistory') || []
    const favorites = wx.getStorageSync('favorites') || []
    const userPlaylists = wx.getStorageSync('userPlaylists') || []
    const settings = wx.getStorageSync('settings') || this.globalData.settings

    if (userInfo) {
      this.globalData.userInfo = userInfo
    }
    this.globalData.playHistory = playHistory
    this.globalData.favorites = favorites
    this.globalData.userPlaylists = userPlaylists
    this.globalData.settings = { ...this.globalData.settings, ...settings }
  },

  // 设置音频事件监听
  setupAudioEvents() {
    this.globalData.audioManager.onPlay(() => {
      this.globalData.isPlaying = true
    })
    
    this.globalData.audioManager.onPause(() => {
      this.globalData.isPlaying = false
    })
    
    this.globalData.audioManager.onEnded(() => {
      // 自动播放下一首
      if (this.globalData.settings.autoPlay) {
        this.playNext()
      }
    })
    
    this.globalData.audioManager.onError((err) => {
      console.error('音频播放错误:', err)
      // 静默处理错误，不显示提示
    })
  },
  
  // 添加到播放历史
  addToHistory(song) {
    if (!song) return
    
    // 去重处理
    const history = this.globalData.playHistory.filter(item => item.id !== song.id)
    
    // 添加到历史记录前面，包含播放次数
    const existingSong = this.globalData.playHistory.find(item => item.id === song.id)
    const playCount = existingSong ? (existingSong.playCount || 1) + 1 : 1
    
    history.unshift({
      id: song.id,
      name: song.name,
      artist: song.artist,
      picUrl: song.picUrl,
      url: song.url,
      playTime: new Date().getTime(),
      playCount: playCount
    })
    
    // 限制历史记录数量为100条
    if (history.length > 100) {
      history.pop()
    }
    
    // 更新全局数据和本地存储
    this.globalData.playHistory = history
    wx.setStorageSync('playHistory', history)
    
    // 更新统计数据
    this.updateStats()
    
    // 触发播放历史变化事件
    if (this.globalData.onHistoryChange) {
      this.globalData.onHistoryChange()
    }
  },

  // 使用统一的收藏工具函数
  addToFavorites(song) {
    const favoritesUtil = require('./utils/favorites')
    const currentUser = this.globalData.userInfo
    
    if (!currentUser) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return false
    }
    
    const result = favoritesUtil.addToFavorites(currentUser.id, song)
    if (result) {
      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      })
      // 更新统计数据
      this.updateStats()
      // 触发收藏变化事件
      if (this.globalData.onFavoriteChange) {
        this.globalData.onFavoriteChange()
      }
    } else {
      wx.showToast({
        title: '已在收藏列表中',
        icon: 'none'
      })
    }
    
    return result
  },

  // 从收藏中移除
  removeFromFavorites(songId) {
    const favoritesUtil = require('./utils/favorites')
    const currentUser = this.globalData.userInfo
    
    if (!currentUser) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return false
    }
    
    const result = favoritesUtil.removeFromFavorites(currentUser.id, songId)
    if (result) {
      wx.showToast({
        title: '已取消收藏',
        icon: 'success'
      })
      // 更新统计数据
      this.updateStats()
      // 触发收藏变化事件
      if (this.globalData.onFavoriteChange) {
        this.globalData.onFavoriteChange()
      }
    }
    
    return result
  },

  // 切换收藏状态
  toggleFavorite(song) {
    const favoritesUtil = require('./utils/favorites')
    const currentUser = this.globalData.userInfo
    
    const result = favoritesUtil.toggleFavorite(currentUser.id, song)
    
    wx.showToast({
      title: result.message,
      icon: result.success ? 'success' : 'none'
    })
    
    // 更新统计数据
    if (result.success) {
      this.updateStats()
      // 触发收藏变化事件
      if (this.globalData.onFavoriteChange) {
        this.globalData.onFavoriteChange()
      }
    }
    
    return result
  },

  // 检查是否已收藏
  isFavorite(songId) {
    const favoritesUtil = require('./utils/favorites')
    const currentUser = this.globalData.userInfo
    
    if (!currentUser) return false
    
    return favoritesUtil.isFavorited(currentUser.id, songId)
  },

  // 保存用户设置
  saveSettings(settings) {
    this.globalData.settings = { ...this.globalData.settings, ...settings }
    wx.setStorageSync('settings', this.globalData.settings)
  },
  
  playSong(song) {
    if (!song) return
    
    try {
      this.globalData.currentSong = song
      this.globalData.audioManager.title = song.name
      this.globalData.audioManager.singer = song.artist
      this.globalData.audioManager.coverImgUrl = song.picUrl || '/assets/default-cover.svg'
      
      // 使用歌曲的URL，如果没有则尝试从API获取
      if (song.url) {
        this.globalData.audioManager.src = song.url
      } else {
        // 尝试从API获取播放URL
        this.getSongUrl(song.id).then(url => {
          this.globalData.audioManager.src = url
        }).catch(error => {
          console.error('获取播放URL失败:', error)
          // 使用默认URL
          this.globalData.audioManager.src = '/assets/audio/default.mp3'
        })
      }
      
      this.globalData.isPlaying = true
      
      // 播放时添加到历史记录
      this.addToHistory(song)
      
    } catch (error) {
      console.error('播放歌曲失败:', error)
      // 静默失败，不显示错误提示
    }
  },
  
  playNext() {
    const currentIndex = this.globalData.currentSongIndex
    const playlist = this.globalData.currentPlaylist
    
    if (playlist && playlist.length > 0) {
      const nextIndex = currentIndex < playlist.length - 1 ? currentIndex + 1 : 0
      const nextSong = playlist[nextIndex]
      
      this.globalData.currentSong = nextSong
      this.globalData.currentSongIndex = nextIndex
      
      this.playSong(nextSong)
    }
  },

  // 获取歌曲播放URL
  async getSongUrl(songId) {
    try {
      const api = require('./utils/api')
      const response = await api.getSongUrl(songId)
      return response.url
    } catch (error) {
      console.error('获取歌曲URL失败:', error)
      // 返回默认URL
      return '/assets/audio/default.mp3'
    }
  },

  // 新增：更新统计数据并通知
  updateStats() {
    const favoritesUtil = require('./utils/favorites')
    const user = this.globalData.userInfo
    
    // 更新收藏数量
    this.globalData.stats.favoriteCount = user 
      ? favoritesUtil.getFavorites(user.id).length 
      : 0
    
    // 更新播放历史数量
    this.globalData.stats.historyCount = this.globalData.playHistory.length
    
    // 更新歌单数量
    this.globalData.stats.playlistCount = this.globalData.userPlaylists.length
    
    // 下载数量（这里简单处理为0，实际项目需要根据下载管理逻辑更新）
    this.globalData.stats.downloadCount = 0
    
    // 触发全局事件通知更新
    if (wx.eventEmitter) {
      wx.eventEmitter.emit('statsUpdated', this.globalData.stats)
    } else {
      console.warn('请确保已实现wx.eventEmitter事件系统')
    }
  }
})